import React, { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Layout, Typography, Menu } from 'antd';
import {
  HomeOutlined,
  BookOutlined,
  SyncOutlined,
  BarChartOutlined,
  MenuOutlined,
} from '@ant-design/icons';
import { UserInfo } from '@/components';
import classNames from 'classnames';
import { useNavigate } from 'react-router-dom';

import { isAuthenticated, getCurrentUser, clearAuthToken } from '@/utils/auth'

import './index.scss';

const { Header } = Layout;
const { Title } = Typography;

const AppHeader = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [currentRoute, setCurrentRoute] = useState()
  const [userInfo, setUserInfo] = useState({
    username: '',
    role: '',
    loginTime: ''
  })



  if (location.pathname === '/login') {
    return null;
  }

  const navItems = [
    {
      to: '/home',
      icon: <HomeOutlined />,
      label: '系统首页',
      exact: true,
    },
    {
      to: '/books',
      icon: <BookOutlined />,
      label: '图书目录',
    },
    {
      to: '/inventory',
      icon: <SyncOutlined />,
      label: '库存管理',
    },
    {
      to: '/order',
      icon: <BarChartOutlined />,
      label: '订单处理',
    },
    {
      to: '/catalog',
      icon: <MenuOutlined />,
      label: '分类管理',
    },
  ];


  const navigateAction = (route) => {
    setCurrentRoute(route.key)
    navigate(route.key)
  }

  const logoutAction = () => {
    clearAuthToken()
    setUserInfo({
      username: '',
      role: '',
      loginTime: ''
    })
    navigate('/login')
  }


  useEffect(() => {
    const user = getCurrentUser()
    if(user) {
      setUserInfo(user)
    }
   
    setCurrentRoute(location.pathname)

  }, []);

  return (
    <Header className='header-container'>
      <div className='header-content-wrapper'>
        <div className='brand-title'>
          <Title level={1} className='brand-title-text'>
            图书馆管理系统
          </Title>
        </div>

        <div className='nav-container-wrapper'>
          <Menu
            mode='horizontal'
            className='navigation-menu'
            onClick={navigateAction}
          >
            {navItems.map(item => (
              <Menu.Item
                key={item.to}
              
                className={classNames('menu-item', {
                  active: currentRoute === item.to,
                })}
                icon={<div className='nav-icon'>{item.icon}</div>}
              >
                <div >
                  <span>{item.label}</span>
                </div>
              </Menu.Item>
            ))}
          </Menu>

          <UserInfo userInfo={userInfo} onLogout={logoutAction}  />
        </div>
      </div>
    </Header>
  );
};

export default AppHeader;
